<?php
function ldapAdd($conn, $add) {
        if (allowedCharacters($_POST['name']) && strlen($_POST['name']) < 25 && strlen($_POST['name']) > 0 ) {
		global $GET;
                switch($add) {
                        case "user":
                                event($conn,"useradd");
				if( !isset($_SESSION['error']) ) {
					$GET['u']=strtolower($_POST['name']);
					info('user_created');
				}
                                break;
                        case "group":
                                event($conn,"groupadd");
				$GET['g']=strtolower($_POST['name']);
				info('group_created');
                                break;
                }
        } else {
        error("allowedchar");
        }
};


function ldapMod($conn, $mod) {
	global $GET;
        switch($mod) {
                case "user":
                        event($conn,"usermod");
			if( isset($_GET['g']) ) {
				$GET['g']=strtolower($_GET['g']);
			}
			else {
				if( isset($_GET['name']) )
					$GET['u']=strtolower($_GET['name']);
				else
					$GET['u']=strtolower($_POST['name']);
			}
                     //om inga fel skett
                        if( !isset($_SESSION['error']) )
                                info('user_mod');
                        break;
                case "usermany":
                        event($conn,"usermodmany");

			if (isset($_GET['users'])) {
				$GET['users']=$_GET['users'];
			} else {
                                $GET['users']='';
				for ($i=1000; $i<2000; $i++) {
					if (isset($_POST['usermany'.$i])) {
						$GET['users'] .= $i.',';
					}
				}
			}
                        break;
                case "group":
                        event($conn,"groupmod");
			if( isset($_GET['g']) )
				$GET['g']=strtolower($_GET['g']);
                     //om inga fel skett
                        if( !isset($_SESSION['error']) )
                                info('group_mod');
                        break;
        };
};


function ldapDel($conn,$del) {
        switch($del) {
                case "user":
                        event($conn,"userdel");
                        info('del_user');

                        function docs() {
                        	require("../services/ldap/doc/ldap.php");
                                docDelUserDone();
                        }
                        break;
		case "usermany":
			foreach( $_POST as $name=>$data ) {
				if ( preg_match('/usermany(\d+)/', $name, $match) ) {
					$uid = $match[1];
					$info = ldap_get_entries($conn, ldap_search($conn, $GLOBALS["dc"], "(uidnumber=$uid)"));
					$_GET['name'] = $info[0]['cn'][0];
					event($conn,"userdel");
				}
			}
			info('del_user');
			break;
		case "group":
                        event($conn,"groupdel");
			info('del_group');
                        break;
        };
};

function ldapImport($conn) {
	global $GET;
	
	if (isset($_POST['b_usermodmany']) AND ($_POST['b_usermodmany'])) {
		$GET['action'] = 'showmany';
		$GET['users'] = $_GET['userstring'];
		$GET['t']='users';


	} elseif ($_POST['action']=='check') {
		unset($_SESSION['import']);

                preg_match_all('/^.*$/m', $_POST['importcsv'], $lines);

		unset($_SESSION['import']['formatted']);
		unset($_SESSION['import']['users']);
		unset($_SESSION['import']['fullnames']);
                
		$usernames = array();
                $_SESSION['import']['formatted'] ='';

		foreach ($lines[0] as $line) {
			// Hämta ut anvnamn och ev Full namn
			if( preg_match('/^[\s\"\']*([^\"\';,\s ]+)[\s\"\']*[;,]?[\s\"\']*([^\"\';,]*).*$/', $line, $matches) != false ) {
				$usernames[] = trim($matches[1]);
				$fname = trim($matches[2]);

				//Byt ut tomt "fullständigt namn" till samma som användarnamn
				if( $fname == "" ) {
					$fname = $matches[1];
				}
				$fullnames[] = $fname;
			}
		}
		$user_count = array_count_values($usernames); // för att senare ange dubletter

		foreach ($usernames as $i=>$u) {
                        $fname = $fullnames[$i];

			$_SESSION['import']['users'][] = $u;
			$_SESSION['import']['fullnames'][] = $fname;

			$_SESSION['import']['formatted'] .= '<tr><td>';
			if(!allowedCharacters($u)) {
				$_SESSION['import']['formatted'] .= '<b style="color:red">'.$u.'</b>&nbsp;&nbsp;: <i>innehåller ogiltiga tecken</i>';
                                $GET['error'] = TRUE;
			}
			elseif( getLdapUser($conn, $u) != false ) {
				$_SESSION['import']['formatted'] .= '<b style="color:orange">'.$u.'</b>&nbsp;&nbsp;: <i>finns redan</i>';
				$GET['error'] = TRUE;
			}
			elseif( $user_count[$u] != 1 ) {
				$_SESSION['import']['formatted'] .= '<b style="color:orange">'.$u.'</b>&nbsp;&nbsp;: <i>dublett</i>';
				$GET['error'] = TRUE;
			}
			else {
				$_SESSION['import']['formatted'] .= $u;
			}
                        $_SESSION['import']['formatted'] .= '</td><td>'.$fname.'</td></tr>';

			$GET['action']='check';
		}
	} elseif ($_POST['action']=='confirm') {

                $userstring='';

		exec('apg -m10 -x12 -MNCL -a0 -n '.count($_SESSION['import']['users']).'',$passwords);
		
		for ($i=0; $i<count($_SESSION['import']['users']); $i++) {
			$u = $_SESSION['import']['users'][$i];
                        $fname = $_SESSION['import']['fullnames'][$i];

			$_POST['name'] = $u;
			$_POST['pass1'] = $_POST['pass2'] = $passwords[$i];

			event($conn, "useradd");

                        unset( $_POST['pass1'] );
			unset( $_POST['pass2'] );
			$_POST['cn'] = $u;
			$_POST['uid'] = "";
			$_POST['displayName']= $fname;
			event($conn, "usermod");

			$_SESSION['import']['user'][$i]['name'] = $u;
                        $_SESSION['import']['user'][$i]['fullname'] = $fname;
			$_SESSION['import']['user'][$i]['password'] = $passwords[$i];

			$sr=ldap_search($conn, $GLOBALS['dc'], '(cn='.$u.')');
			$info = ldap_get_entries($conn, $sr);
			$_SESSION['import']['user'][$i]['uidnumber'] = $info[0]['uidnumber'][0];

			$userstring .= $info[0]['uidnumber'][0].',';

		}

		$GET['userstring'] = rtrim($userstring,',');
		$GET['action']='confirm';
		$_SESSION['import']['done'] = true;
	}
};


///////////////////////////////
///////////////////////////////

$conn = ldapConnect();

  // IMPORT
if( isset($_GET['t']) AND ($_GET['t'] == "import")) {
	ldapImport($conn);
}
  // GROUP
elseif( isset($_GET['t']) AND ($_GET['t'] == "groups")) {
	if( isset($_POST['b_add']) )
		ldapAdd($conn, "group");
	else if( isset($_POST['b_del']) || isset($_GET['del']) )
		ldapDel($conn, "group");
	else {
		if( $_GET['mod'] == "user" ) 
                	ldapMod($conn, "user");
		else
			ldapMod($conn, "group");
	}
}
  // USER
else {
	if( isset($_POST['b_add']) ) {
                ldapAdd($conn, "user");
	} else if( isset($_POST['b_modmany']) AND ($_POST['b_modmany'] == 'TRUE') ) {
                ldapMod($conn, "usermany");
	} else if( isset($_POST['b_delmany']) AND ($_POST['b_delmany'] == 'TRUE') ) {
                ldapDel($conn, "usermany");
        } else if( isset($_POST['b_del']) || isset($_GET['del']) ) {
                ldapDel($conn, "user");
        } else {
                ldapMod($conn, "user");
	}
}

ldap_close($conn);
?>
